<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="close"
      :title="title"
      width="800px"
      :top="'10vh'"
    >
      <el-form ref="form" :model="form" size="small" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="服务名称"
              prop="name"
              :rules="[{ required: true, message: '请输入数据项名称', trigger: 'blur' }]"
              style="width: 100%"
            >
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示图标" prop="appIcon">
              <el-popover
                placement="bottom-start"
                width="450"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <el-button slot="reference" size="small" style="padding: 0px;">
                  <el-image
                    v-if="form.icon"
                    :src="form.icon"
                    style="height: 32px;width: 32px;"
                  />
                  <i v-else style="font-size: 20px;height: 32px;width: 32px;line-height: 32px" class="el-icon-plus" />
                </el-button>
                <server-image-select ref="iconSelect" :fall-back-function="'selected'" @selected="selected" />
              </el-popover>
              <el-input v-model="form.icon" type="hidden" style="width: 200px" placeholder="点击选择图标" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图" prop="backImage">
              <div class="schoolBottomImage" @click="schoolBackgroundImage">
                <img v-if="form.backImage" :src="form.backImage" class="school-bak-image">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </div>
              <el-input v-model="form.backImage" type="hidden" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="相关附件">
              <el-upload
                class="upload-demo"
                :action="baseUrl+'rest/api/config/v1/file/custom/upload?type=10&fs=1'"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                multiple
                accept=".xls,.xlsx,.doc,.docx,.zip,.jpg,.png"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传.xls,.xlsx,.doc,.docx,.pdf,.zip,.jpg,.png，且不超过10Mb</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="简介"
              prop="summary"
              :rules="[{ required: true, message: '请输入服务简介', trigger: 'blur' }]"
            >
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="请输入简介"
                maxlength="150"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务说明" prop="explain" :rules="[{ required: true, message: '请输入专项服务说明', trigger: 'blur' }]">
              <wang-editor v-model="form.explain" :is-clear="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.state">
                <el-radio
                  v-for="item in status"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="排序"
              prop="px"
              style="width: 100%"
            >
              <el-input-number v-model="form.px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="close">取消</el-button>
        <el-button :loading="loading" type="primary" @click="save('form')">确认</el-button>
      </div>
    </el-dialog>
    <!--  页脚背景图片剪切  -->
    <el-dialog :visible.sync="dialogTableVisible" width="70%">
      <cropper-image
        ref="child"
        :name="cropperName"
        :auto-crop-height="autoCropHeight"
        :auto-crop-width="autoCropWidth"
        :fixed-number="fixedNumber"
        append-to-body
        @uploadImgSuccess="handleUploadSuccess"
      />
    </el-dialog>
  </div>
</template>
<script>
import { saveObject, updateObject } from '@/api/yslb/index'
import { delObject, queryAllFj } from '@/api/yslb/fj'
import ServerImageSelect from '@/components/ServerImageSelect'
import CropperImage from '@/common/cropper/index'
import WangEditor from '@/components/wangEdit'
export default {
  name: 'LeftEntity',
  components: { ServerImageSelect, CropperImage, WangEditor },
  data() {
    return {
      fileList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      cropperName: '封面图上传',
      fixedNumber: [4.6, 1],
      autoCropHeight: 50,
      autoCropWidth: 50,
      title: '数据项管理',
      loading: false,
      testLoading: false,
      dialogFormVisible: false,
      dialogTableVisible: false,
      dataSources: [],
      status: [{ id: 0, value: false, label: '禁用' },
        { id: 1, value: true, label: '启用' }],
      form: {
        id: null,
        name: null,
        summary: '',
        icon: null,
        backImage: '',
        explain: '',
        state: true,
        sfsc: false,
        fjList: [],
        px: 0
      },
      queryData: null
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过10MB!')
      }
      return isLt2M
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      if (fileList === null || fileList.length === 0) {
        this.form.fjList = []
      } else {
        const lists = fileList.map(item => {
          if (undefined !== item.response) {
            return { fileName: item.response.data.name, id: item.response.data.id, url: item.response.data.url, suffix: item.response.data.ext,
              path: item.response.data.path, size: item.response.data.size }
          } else {
            return { fileName: item.fileName, id: item.id, url: item.url, path: item.path, size: item.size, suffix: item.suffix }
          }
        })
        this.form.fjList = lists
      }
    },
    handleRemove(file, fileList) {
      if (undefined === file.response) {
        if (file.id !== null) {
          const ids = []
          ids.push(file.id)
          delObject(ids).then(res => {
          }).catch(error => {
            console.log(error)
          })
        }
      }
      if (fileList === null || fileList.length === 0) {
        this.form.fjList = []
      } else {
        const lists = fileList.map(item => {
          if (undefined !== item.response) {
            return { fileName: item.response.data.name, id: item.response.data.id, url: item.response.data.url, suffix: item.response.data.ext,
              path: item.response.data.path, size: item.response.data.size }
          } else {
            return { fileName: item.name, id: item.id, url: item.url, path: item.path, size: item.size, suffix: item.suffix }
          }
        })
        this.form.fjList = lists
      }
    },
    handleUploadSuccess(data) {
      this.form.backImage = data.url
      this.dialogTableVisible = false
    },
    schoolBackgroundImage() {
      this.cropperName = 'handleUploadBackgroundSuccess'
      this.dialogTableVisible = true
    },
    initAllFl() {
      queryAllFj({ gid: this.form.id }).then(res => {
        const { data } = res
        this.fileList = []
        if (data !== null && data.length > 0) {
          this.fileList = data.map(item => {
            return { name: item.fileName, id: item.id, url: item.url, path: item.path, size: item.size, suffix: item.suffix }
          })
        }
        this.form.fjList = data
      })
    },
    selected(name) {
      this.form.icon = name.url
    },
    openEntity(data) {
      if (undefined !== data && undefined !== data.id && data.id !== null) {
        this.form = Object.assign({}, data)
        this.title = '修改数据项信息'
        this.initAllFl()
        this.dialogFormVisible = true
      } else {
        this.title = '新增数据项信息'
        this.dialogFormVisible = true
      }
    },
    save(formName) {
      this.loading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id !== null && undefined !== this.form.id) {
            updateObject(this.form).then(res => {
              this.$message.success('更新成功！')
              this.close()
            }).catch(() => {
              this.loading = false
              this.$message.error('更新失败！')
            })
          } else {
            saveObject(this.form).then(res => {
              this.$message.success('保存成功！')
              this.close()
              this.loading = false
            }).catch(() => {
              this.loading = false
              this.$message.error('保存失败！')
            })
          }
        } else {
          this.loading = false
          console.log('error submit!!')
          return false
        }
      })
    },
    close() {
      this.loading = false
      this.fileList = []
      Object.assign(this.$data.form, this.$options.data.call(this).form)
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
      this.$emit('fetch-data')
    }
  }
}
</script>

<style scoped>
.schoolBottomImage {
  width: 100%;
  height: 250px;
  border: 1px dashed #9b9b9b;
  border-radius: 4px;
  text-align: center;
  line-height: 250px;
  font-size: 34px;
}
.school-bak-image {
  width: 100%;
  height: 100%;
}
</style>
